<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_User extends Controller_Admin {
    public function action_index()
    {
        $quer=$this->request->query('username');
        if($quer)
        {
         $usr = ORM::factory('user')
             ->where('username', 'like', "%".$quer."%")
             ->find_all();
        }
        else
        {
         $usr=ORM::factory('user')->find_all();
        }
        
         $this->template->users =$usr;
    }
     
     public function action_delete()
     {         
         $this->template->act = $this->request->action();
         $members = ORM::factory('user',(int)$this->request->param('id',0))
                 ->delete();
         HTTP::redirect('admin_user');
     }
     
     public function action_edit()
     {
         $this->template->act =$this->request->action();
         $this->template->content ='admin_user/form';
         $members = ORM::factory('user', (int)$this->request->param('id',0));
        $members_info = ORM::factory('info_user', (int)$this->request->param('id',0));
          $this->_save($members);
          
     }
     public function action_add()
     {  
        $this->template->act = $this->request->action();
        $this->template->content ='admin_user/form';
        $this->_save(ORM::factory('user'));
        
     }
     
     private function _save($members)
     {  
        
        $post = $this->request->post();
        if (isset($post['username']))
        {
            
         try{        
             $extrarules = null;
                $members->username =    $post['username'];        
                $members->email =       $post['email'];
                if($members->password !=''|$this->template->act =='add')
                {   
                   $members->password =$post['password'];
                   $this->password_confirm =  $post['validation_password'];
                   $extrarules = Validation::factory($_POST)
                           ->rule('password_confirm','matches',array(':validation','validation_password','password'));                
                }
                $members->save($extrarules);
            }
            catch(ORM_Validation_Exception $e)
            {
                $t=$e->errors('validation');
                var_dump($t);
                $this->template->errors = $t;
            }
        }       $post=$this->request->post();                
                $this->template->users = $members;
                if(isset($post['register']))
                {
                //HTTP::redirect("admin_user/index");
                }
     }
}
